<?php
namespace Admin\Controller;

class VersionController extends BaseController {


    public function index() {

        $versionList = M ('Version')->order('version_string desc, addtime desc')->select();

        $updateSwitch = D ('Appconfig')->get('update_switch');

        $this->assign('updateSwitch',$updateSwitch);
        $this->assign('versionList',$versionList);
        $this->display();
    }


    public function add() {

        if (!IS_POST) {
            // 获取当前最新版本号
            $versionString = M ('Version')->order('version_string desc')->limit(1)->getField('version_string');
            empty($versionString) && $versionString = "无";

            $this->assign('versionString',$versionString);
            $this->display();
        } else {

            $data['version_string'] = I ('request.version_string');
            $data['update_force'] = I ('request.update_force');
            $data['download_url'] = I ('request.download_url');

            if (($flag = \Api\Libs\HttpVerifyUtil::verifyFormParamNotNull($data) !== "000000"))
                $this->out('RESULT_FAIL',\Api\Libs\ExplainRespCodeUtil::explain($flag));

            $data['server_url'] = I ('request.server_url');
            $data['remark'] = I ('request.remark');
            $data['addtime'] = date('Y-m-d H:i:s');
            $data['download_url'] = $this->domain . $data['download_url'];

            $Version = D ('Version');
            if ($Version->checkRepeat($data['version_string']))
                $this->out('RESULT_FAIL','版本重复');

            $flag = $Version->add($data);
            if ($flag === false)
                $this->out('RESULT_FAIL','发布新版本失败');
            $this->out('RESULT_OK','',__CONTROLLER__);
        }

    }


    public function del() {

        if (IS_POST) {
            $id = I ('request.id');
            if (empty($id))
                $this->error('错误的参数');

            if (M ('Version')->delete($id) !== false)
                $this->out('RESULT_OK','删除成功',__CONTROLLER__);
            $this->error('RESULT_FAIL','删除失败');
        }
    }



    public function updateSwitch() {
        if (IS_POST) {
            $val = (int) I ('post.val');

            if (D ('Appconfig')->set('update_switch',$val))
                $this->out('RESULT_OK','修改成功');
            $this->out('RESULT_FAIL','修改失败');
        }
    }

    /**
     * 上传apk文件
     */
    public function upload() {
        $Upload = new \Api\Libs\Upload();
        $res = $Upload->upload('apk');
        $this->ajaxReturn($res);
    }
}